#! /usr/bin/env perl

###########################################################################
#
# vnew
#
###########################################################################
#
# This command adds and then commits its args to VC.  Generally, you will probably want to use vcommit, since
# it will handle unknown files and do the same thing.  However, vnew has two advantages over vcommit:
#
# 1) It doesn't ask you if it's okay to add the file every time it finds one.  For large numbers of files that
# you already know are new, you don't want to be asked about every one.
#
# 2) vcommit won't add whole directories worth of new files, even with -r.  vnew -r works fine.
#
# OTOH, vnew won't let you commit both new and existing files at once, which vcommit will.  So choose
# whichever one is best for you.
#
# #########################################################################
#
# All the code herein is released under the Artistic License
#		( http://www.perl.com/language/misc/Artistic.html )
# Copyright (c) 2000-2011 Barefoot Software, Copyright (c) 2004-2007 ThinkGeek
#
###########################################################################

use strict;
use warnings;

use VCtools::Base;
use VCtools::Args;
use VCtools::Common;


#################################
# OPTIONS AND ENVIRONMENT VARS
#################################

VCtools::switch('recursive', 'r', 'operate recursively');
VCtools::args('files', 'list', 'file(s) (or directory/ies) to add to VC');
VCtools::getopts();

# remember, directories are files too
my @files = VCtools::files();


#################################
# CHECK FOR ERRORS
#################################

my $proj = VCtools::verify_files_and_group(@files);

# get statuses for everything at once (quicker that way)
VCtools::cache_file_status(@files);

my @files_to_add;
foreach my $file (@files)
{
	if (VCtools::exists_in_vc($file))
	{
		print STDERR "not adding file to list\n" if DEBUG >= 3;
		VCtools::fatal_error("$file is already in VC") unless VCtools::ignore_errors();
	}
	else
	{
		print STDERR "adding file to list\n" if DEBUG >= 3;
		push @files_to_add, $file;
	}
}
print STDERR "files_to_add: @files_to_add\n" if DEBUG >= 2;


#################################
# MAIN
#################################

my @new_files;
if (@files_to_add)
{
	@new_files = VCtools::add_files(@files_to_add, { DONT_RECURSE => not VCtools::recursive() } );

	# theoretically, we should only see new files in the case of a recursive add
	# let's ask the user if this is okay with them
	# (if not, we'll just revert the adds)
	if (@new_files)
	{
		VCtools::list_files("have been added unexpectedly", @new_files);
		unless (VCtools::yesno("is this okay?"))
		{
			VCtools::revert_files(@new_files, @files);
			VCtools::info_msg("no files have been added");
			exit;
		}
	}
}

VCtools::commit_files($proj, @files, @new_files);

print "done\n" unless $?;
